package yzy.ecps.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import yzy.ecps.dao.SkuDao;
import yzy.ecps.model.BtcSku;
import yzy.ecps.model.Cart;
import yzy.ecps.model.ShopCart;
import yzy.ecps.service.CartService;
import yzy.ecps.utils.EcpsUtils;

@Service
public class CartServiceImpl implements CartService {
	@Autowired
	private SkuDao skuDao;
	
	@SuppressWarnings("unchecked")
	public void addCart(HttpServletRequest request,
			HttpServletResponse response, Long skuId,Integer quantity) throws IOException {
		//获取购物车cookie
		Cookie cartCookie = getCartCookie(request);
		//如果还不存在购物车cookie,则创建
		List<JSONObject> list = null;
		if(cartCookie == null ||cartCookie.getValue()==null || cartCookie.getValue().trim().equals("")){
			list = new ArrayList<>();
			JSONObject json = new JSONObject();
			json.accumulate("skuId", skuId);
			json.accumulate("quantity", quantity);
			list.add(json);
			cartCookie = new Cookie(EcpsUtils.getValueByKeyFormSysProperties("cart_key"), list.toString());
			
		}
		else{
			boolean flag = false;
			list = JSONArray.fromObject(cartCookie.getValue());
			//两种情况：当前sku还未添加过购物车和cookie中已经存在该sku
			//遍历json集合
			for (JSONObject json : list) {
				//如果skuId和传入的skuId相等则说明存在该sku
				if(json.getLong("skuId")== skuId){
					Integer n = json.getInt("quantity");
					json.remove("quantity");
					json.accumulate("quantity", n+quantity);
					flag = true;
					break;
				}
				
			}
			if(!flag){
				JSONObject newJson = new JSONObject();
				newJson.accumulate("skuId", skuId);
				newJson.accumulate("quantity", quantity);
				list.add(newJson);
			}
		}
		cartCookie.setPath("/");
		cartCookie.setMaxAge(Integer.MAX_VALUE);
		cartCookie.setValue(list.toString());
		response.addCookie(cartCookie);
	}

	public String validCookie(HttpServletRequest request,
			HttpServletResponse response) {
		boolean flag = false;
		//向cookie中存入一条测试数据 ，如果取出来的值和存入的一样，则没有被禁用
		Cookie cookie = new Cookie("test", "test");
		//设置该cookie在该网站的path
		cookie.setPath("/");
		//向浏览器写入cookie
		response.addCookie(cookie);
		
		//获取该网站的所有cookie
		Cookie[] cookies = request.getCookies();
		for (Cookie ck : cookies) {
			if("test".equals(ck.getName()) && "test".equals(ck.getValue())){
				flag = true;
				break;
			}
		}
		return flag?"yes":"no";
	}

	@SuppressWarnings("unchecked")
	public void updateCart(HttpServletRequest request,
			HttpServletResponse response, Long skuId, Integer quantity) throws IOException {
		Cookie cartCookie = getCartCookie(request);
		List<JSONObject> list = JSONArray.fromObject(cartCookie.getValue());
		//遍历json集合
		for (JSONObject json : list) {
			if(json.containsKey("skuId")){
				//如果skuId和传入的skuId相等则返回这个json对象
				if(json.getLong("skuId")== skuId){
					json.remove("quantity");
					json.accumulate("quantity", quantity);
				}
			}
		}
		cartCookie.setValue(cartCookie.toString());
		response.addCookie(cartCookie);
	}

	@SuppressWarnings("unchecked")
	private JSONObject validSku(Cookie cartCookie, Long skuId) throws IOException {
		if(cartCookie==null) return null;
		if(cartCookie.getValue()!=null && !cartCookie.getValue().trim().equals("")){
			List<JSONObject> list = JSONArray.fromObject(cartCookie.getValue());
			//遍历json集合
			for (JSONObject json : list) {
				if(json.containsKey("skuId")){
					//如果skuId和传入的skuId相等则返回这个json对象
					if(json.getLong("skuId")== skuId){
						return json;
					}
				}
			}
		}
		//没有找到相等的ID则返回null
		return null;
	}

	public Cookie getCartCookie(HttpServletRequest request) throws IOException {		
		Cookie[] cookies = request.getCookies();
		if(cookies != null && cookies.length>0){
			for (Cookie cookie : cookies) {
				if(EcpsUtils.getValueByKeyFormSysProperties("cart_key").equals(cookie.getName()))
					return cookie;
			}
		}
		return null;
	}

	public String validStock(HttpServletRequest request, Long skuId, Integer quantity)
			throws Exception {
		
		Integer oldStock = 0;
		
		Cookie cartCookie = getCartCookie(request);
		
		//从购物车中获取指定sku的json对象
		JSONObject json = validSku(cartCookie, skuId);
		if(json != null){
			oldStock += json.getInt("quantity");
		}
		Integer inventory = skuDao.getStockById(skuId);
		
		if(oldStock+quantity > inventory)
			return "no";
		return "yes";
	}

	@SuppressWarnings("unchecked")
	public List<ShopCart> getCartInfo(HttpServletRequest request)
			throws Exception {
		List<ShopCart> cartList = new ArrayList<>();
		Cookie cartCookie = getCartCookie(request);
		if(cartCookie!=null&&cartCookie.getValue()!=null&&!cartCookie.getValue().trim().equals("")){
			List<JSONObject> list = JSONArray.fromObject(cartCookie.getValue());
			for (JSONObject json : list) {
				Long skuId = json.getLong("skuId");
				Integer quantity = json.getInt("quantity");
				BtcSku sku = skuDao.getById(skuId);
				ShopCart cart = new ShopCart();
				cart.setQuantity(quantity);
				cart.setSku(sku);
				cart.setSkuId(skuId);
				cartList.add(cart);
			}
		}
		return cartList;
	}
	
	@SuppressWarnings("unchecked")
	public List<Cart> getCartGroupByGoods(HttpServletRequest request) throws IOException{
		List<ShopCart> carts = new ArrayList<>();
		Cookie cartCookie = getCartCookie(request);
		List<JSONObject> list = JSONArray.fromObject(cartCookie.getValue());
		for (JSONObject json : list) {
			Long skuId = json.getLong("skuId");
			Integer quantity = json.getInt("quantity");
			BtcSku sku = skuDao.getById(skuId);
			ShopCart cart = new ShopCart();
			cart.setQuantity(quantity);
			cart.setSku(sku);
			cart.setSkuId(skuId);
			carts.add(cart);
		}
		List<Cart> cartList = groupCarts(carts);
		
		return cartList;
	}
	
	private List<Cart> groupCarts(List<ShopCart> carts){
		List<Cart> cartList = new ArrayList<>();
		
		long id = 0;
		for (int i = 0; i < carts.size()-1; i++) {
			long aId = carts.get(i).getSku().getGoodsId();
			for (int j = i+1; j < carts.size(); j++) {
				long bId = carts.get(j).getSku().getGoodsId();
				if(aId != id){
					if(aId == bId){
						Cart cart = new Cart();
						cart.setGoodsId(aId);
						cart.setGoodsImg(carts.get(j).getSku().getGoods().getImgRelativePath());
						cart.setGoodsName(carts.get(j).getSku().getGoods().getGoodsName());
						cart.setGoodsNum(carts.get(j).getSku().getGoods().getGoodsNum());
						cart.setGoodsPath(carts.get(j).getSku().getGoods().getStaticPath());
						cartList.add(cart);
						id = aId;
					}
				}
			}
		}
		for (int j = 0; j < cartList.size(); j++) {
			for (int i = 0; i < carts.size(); i++) {
				if(carts.get(i).getSku().getGoodsId().equals(cartList.get(j).getGoodsId())){
					cartList.get(j).getCarts().add(carts.get(i));
				}
			}
		}
		return cartList;
	}

	
	@SuppressWarnings("unchecked")
	public void deleteCart(HttpServletRequest request,
			HttpServletResponse response, Long skuId) throws Exception {
		
		Cookie cartCookie = getCartCookie(request);
		List<JSONObject> jsons = JSONArray.fromObject(cartCookie.getValue());
		for (int i=jsons.size()-1;i>=0;i--) {
			if(jsons.get(i).getLong("skuId")==skuId){
				jsons.remove(i);
			}
		}
		cartCookie.setValue(null);
		cartCookie.setValue(jsons.toString());
		response.addCookie(cartCookie);
	}

	
	public void clearCart(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Cookie[] cookies = request.getCookies();
		Cookie cartCookie = null;
		if(cookies != null && cookies.length>0){
			for (Cookie cookie : cookies) {
				if(EcpsUtils.getValueByKeyFormSysProperties("cart_key").equals(cookie.getName()))
					cartCookie = cookie;
			}
		}
		cartCookie.setValue("");
		response.addCookie(cartCookie);
	}
}
